package proxy;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import tx.TransactionManager;

import java.lang.reflect.Method;

public class CGlibDynamicProxy implements MethodInterceptor {
    //    定义一个目标对象
    private Object target;

    //    完成额外操作的对象，事物模块的对象
    private TransactionManager tx;

    public Object getProxy(){
        Enhancer enhancer=new Enhancer();
        //设置目标对象为代理对象的父类
        enhancer.setSuperclass(target.getClass());
        //设置一个回调函数
        enhancer.setCallback(this);
        //创建一个代理对象
        return enhancer.create();



    }
    public CGlibDynamicProxy(Object target, TransactionManager tx) {
        this.target = target;
        this.tx = tx;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        tx.open1();

        Object result=method.invoke(target,objects);

        tx.commit();
        return null;
    }
}






















